package handler.store.ind.shpp

import com.alibaba.fastjson.JSON

import service.wx.WxUserLocal
import service.wx.WxSignature
import service.wx.WxApi
import service.wx.WxPay

import util.Utils

import service.store.ind.SockClientInfo

import org.paic.d.D

import org.paic.vertx.httpwrapper.render.Render
import org.paic.vertx.httpwrapper.render.Smarty4jRender


// must match /wx/pay/***
handler.get('/wx/pay/shop__:id'){req, resp ->
	String id = req.params.id
	if(!id || !Utils.isIdValid(id)){
		resp.render('/wx/ind/index-error.html', [errmsg: 'not-valid'])
		return
	}

	def userSession = req.session('shop-user')
	if(!userSession){
		resp.render('/wx/ind/index-error.html', [errmsg: 'need-login'])
		return
	}
	String openid = userSession.openid

	def user = WxUserLocal.getUserCached(openid)
	if(user.errcode){
		resp.render('/wx/ind/index-error.html', user)
		return
	}

	def d = D.gen()
	def item = d.queryMap('select * from t_shop_detail where id = ?', 
		[id])
	if(!item){
		resp.render('/wx/ind/index-error.html', [errmsg: 'shop not exists'])
		return
	}

	def userSaved = [:]
	userSaved.nickname = user.nickname
	userSaved.headimgurl = user.headimgurl

	Map r = [:]
	r.timeend = '' + System.currentTimeMillis()
	r.userSaved = JSON.toJSONString(userSaved)

	r.putAll(item)

	def itemList = d.query('select * from t_shop_item where shop_id = ? order by seq asc, dd desc', 
		[id])
	r.itemList = itemList

	if(itemList){
		def topItemList = itemList.grep{it.picTop}.collect{[id: it.id, picTop: it.picTop]}
		r.topItemList = topItemList
	}

	// jssdk
	String ua = req.headers.get('User-Agent')
	boolean isWx = WxApi.isReqFromWx(ua)
	if(isWx){
		Map jsapiInfo = WxSignature.getJsapiInfo(WxSignature.conf.urlHost + req.uri)
		r.putAll(jsapiInfo)
	}

	r.concatJs = 'true' == WxSignature.conf.concatJs
	r.wxDebug = 'true' == WxSignature.conf.wxDebug
	resp.render('/wx/ind/shop/index.html', r)
}

handler.get('/wx/ind/shop/index/:id'){req, resp ->
	String id = req.params.id
	if(!id || !(id ==~ /^\d+$/)){
		resp.render('/wx/ind/index-error.html', [errmsg: 'not-valid'])
		return
	}

	String code = req.params.code
	if(!code){
		resp.render('/wx/ind/index-reject.html', [:])
		return
	}

	String ua = req.headers.get('User-Agent')
	boolean isWx = WxApi.isReqFromWx(ua)
	if(isWx){
		def info = WxSignature.getAccessTokenInfo4Auth(code)
		if(info.errcode){
			resp.render('/wx/ind/index-error.html', info)
			return
		}

		def user = WxApi.getUserInfo4Auth(info.access_token, info.openid)
		if(user.errcode){
			resp.render('/wx/ind/index-error.html', user)
			return
		}

		if(user.openid){
			WxUserLocal.update(user)
			req.session('shop-user', user)
		}

		resp.redirect('/wx/pay/shop__' + id + '?showwxpaytitle=1')
	}else{
		// local test
		req.session('shop-user', [openid: WxSignature.conf.testOpenid])
		resp.redirect('/wx/pay/shop__' + id + '?showwxpaytitle=1')
	}
}

// 订单的再次支付
handler.get('/wx/ind/shop/pay-ag'){req, resp ->
	def userSession = req.session('shop-user')
	if(!userSession){
		resp.json([flag: false, tips: 'user-login'])
		return
	}
	String openid = userSession.openid

	String id = req.params.id
	if(!id || !Utils.isIdValid(id)){
		resp.json([flag: false, tips: 'parameter'])
		return
	}

	def d = D.gen()

	def order = d.queryMap('select * from t_shop_pay_order where id = ? and openid = ?', [id, openid])
	if(!order || !order.prepayId){
		resp.json([flag: false, tips: 'order-not-exists'])
		return
	}

	def jsPayParams = WxPay.genPayJsParams(order.prepayId)
	jsPayParams.flag = true
	resp.json(jsPayParams)
}

// 生成订单
handler.post('/wx/ind/shop/apply'){req, resp ->
	def userSession = req.session('shop-user')
	if(!userSession){
		resp.json([flag: false, tips: 'user-login'])
		return
	}
	String openid = userSession.openid

	req.jsonHandler{json ->
		List itemList = json.itemList
		if(!itemList){
			resp.json([flag: false, tips: 'item-list-required'])
			return
		}

		int amount = 0
		for(one in itemList){
			amount += one.qt * one.price
		}

		// max 5k
		if(amount <= 0 || amount > 5 * 1000){
			resp.json([flag: false, tips: 'amount-rangeout'])
			return
		}
		
		Map item = [:]
		item.amount = amount
		item.openid = openid
		item.tradeNo = WxPay.generateNonce()
		
		log.info('' + item)
		log.info('' + itemList)

		def d = D.gen()

		// 冗余数据，商品名称
		String itemIds = itemList.collect{'' + it.id}.grep{it ==~ /^\d+$/}.join(',')
		def itemListQueryed = d.query("select id, title from t_shop_item where id in (${itemIds})")
		if(!itemListQueryed){
			resp.json([flag: false, tips: 'item-list-required'])
			return
		}

		for(one in itemList){
			def sub = itemListQueryed.find{('' + it.id) == ('' + one.id)}
			if(sub){
				one.title = sub.title
			}
		}
		item.detail = JSON.toJSONString(itemList)

		int orderId = d.add(item, 't_shop_pay_order')

		for(one in itemList){
			def detailOne = [:]
			detailOne.openid = openid

			detailOne.orderId = orderId
			detailOne.itemId = one.id
			detailOne.price = one.price
			detailOne.qt = one.qt

			d.add(detailOne, 't_shop_pay_order_detail')
		}

		String ua = req.headers.get('User-Agent')
		boolean isWx = WxApi.isReqFromWx(ua)

		boolean isOk = false

		if(isWx){
			def params = [:]

			params.openid = openid
			params.totalFee = amount * 100
			params.body = 'shop pay'
			params.tradeNo = item.tradeNo
			params.ip = '8.8.8.8'

			def r = WxPay.genPostParams(params)
			String prepayId = WxPay.getPrepayId(r)

			if(!prepayId){
				resp.json([flag: false, tips: 'wx-order-failed'])
				return
			}
			d.update([id: orderId, prepayId: prepayId], 't_shop_pay_order', null)

			def jsPayParams = WxPay.genPayJsParams(prepayId)
			jsPayParams.flag = true
			resp.json(jsPayParams)

			isOk = true
		}else{
			resp.json([flag: true])

			isOk = true
		}

		// websocket notify
		if(isOk){
			// TODO
			String openidShopManager = WxSignature.conf.testOpenid
			String sockid = SockClientInfo.inst.get(openidShopManager + '-sockid')
			if(sockid){
				handlerSockjs.send(sockid, [action: 'order-refresh'])
			}

		}
	}
}

// ***
handler.get('/wx/ind/shop/get-order-list'){req, resp ->
	def userSession = req.session('shop-user')
	if(!userSession){
		resp.json([flag: false, tips: 'user-login'])
		return
	}
	String openid = userSession.openid

	def d = D.gen()

	def ll = d.query('select * from t_shop_pay_order where openid = ? order by dd desc limit 100', 
		[openid])

	resp.json([ll: ll])
}

handler.get('/wx/ind/shop/item/:id'){req, resp ->
	def user = req.session('shop-user')
	if(!user){
		resp.json([flag: false, tips: 'user-login'])
		return
	}

	String id = req.params.id
	if(!id || !Utils.isIdValid(id)){
		resp.json([flag: false, tips: 'parameter'])
		return
	}

	def d = D.gen()

	def one = d.queryMap('select * from t_shop_item where id = ?', 
		[id])
	if(!one){
		resp.json([flag: false, tips: 'item-not-exists'])
		return
	}
	def ll = d.query('''
		select aa.*,bb.nickname from 
			(select a.* from t_shop_pay_order_detail a where a.item_id = ? and dd_comment is not null order by dd_comment desc) aa 
			left join wx_user bb on aa.openid = bb.openid
	'''
	, [id])

	Render render = new Smarty4jRender()

	String innerMain = render.render(config.webroot + '/wx/ind/shop/item-detail-main.html', [one: one])
	String innerComment = render.render(config.webroot + '/wx/ind/shop/item-detail-comment.html', [ll: ll])

	resp.json([id: id, commentNum: one.commentNum, 
		innerMain: innerMain, innerComment: innerComment, 
		objJson: JSON.toJSONString(one)])
}